const express = require("express");
// 创建路由器对象
const a = express.Router();
// 引入第三方连接池模块
const pool = require("../pool/pool");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const key = "my key";
const nodemailer = require("nodemailer");
const Auth = require("../middlewares/Auth");
const { generateToken } = require("../core/utils");
// 图片上传
const multer = require("multer");
const fs = require("fs");
const moment = require("moment");
const uuid = require("uuid");
const path = require("path");
const { send } = require("process");
const { secretKey } = require("../config/config");
const { verifyToken } = require("../middlewares/Auth");
let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/upload");
  },
  filename: function (req, file, cb) {
    let filename = file.originalname;
    let extension = filename
      .substr(filename.lastIndexOf(".") + 1)
      .toLowerCase();
    let dirname = moment().format("Y-MM-DD");
    let mainname = uuid.v1();
    filename = mainname + "." + extension;
    cb(null, filename);
  },
});

const upload = multer({ storage: storage });
//********************************* *//
// 1.管理员登录
a.post("/login", (req, res, next) => {
  let obj = req.body;
  // console.log(obj)
  let sql = "select * from admin where a_name=? and a_pwd=?";
  pool.query(sql, [obj.aname, obj.apwd], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    // console.log(data)
    if (data.length !== 0) {
      const token = generateToken(data[0].a_id, 5);
      res.send({
        code: "200",
        msg: "登陆成功",
        token: token,
        admin_id: data[0].a_id,
        data: data[0],
      });
    } else {
      res.send({ code: "201", msg: "登陆失败！" });
    }
  });
});
// 2.获取车辆信息内容
a.post("/agetdatacar", (req, res, next) => {
  let sql = "select * from  car ";
  const token = (req.headers.authorization || "").slice(7);
  // const decode = jwt.verify(token, secretKey);
  // console.log(token);
    if(verifyToken(token)){
      pool.query(sql, (err, data) => {
        if (err) {next(err);return;}
        res.send({ code: "200", data: data });
      });
    }else{
      res.send({"code":402,"msg":"未合法登录!"})
    }

  
});

// 3.增加车辆
a.post("/uploadcardata", upload.fields([{ name: "file" }]), (req, res) => {
  let baseURL = `http://localhost:3000/upload/${req.files.file[0].filename}`;
  let obj = req.body.data.split(",");
  let sql = "insert into car values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
  let cartypeid = parseInt(obj[10]);
  let price = parseInt(obj[6]);
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
    pool.query(
      sql,
      [
        ,
        obj[0],
        `${baseURL}`,
        obj[1],
        obj[2],
        obj[3],
        obj[4],
        obj[5],
        price,
        obj[7],
        obj[8],
        obj[9],
        cartypeid,
      ],
      (err, data) => {
        if (err) {
          next(err);
          return;
        }
        console.log(data);
        if (data.affectedRows == 1) {
          res.send({ code: "200", msg: "新增车辆成功!" });
        }
      }
    );
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }

});
// 4.删除车辆
a.post("/deletecar", (req, res, next) => {
  obj = req.body;
  // console.log(obj)
  let sql = "delete from car where car_id = ?";
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
      pool.query(sql, [obj.id], (err, data) => {
    if (data.affectedRows == 1) {
      res.send({ code: "200", msg: "删除成功!" });
    } else {
      res.send({ code: "201", msg: "删除失败!" });
    }
  });
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }

});
// 5.获取订单信息
a.post("/getdataorder", (req, res, next) => {
  let sql = "select * from car_order";
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
      pool.query(sql, (err, data) => {
    if (err) {
      next(err);
      return;
    }
    res.send({ code: "200", data: data });
  });
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }

});
// 6.获取用户信息
a.post("/getdatauser", (req, res, next) => {
  let sql = "select * from user";
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
      pool.query(sql, (err, data) => {
    if (err) {
      next(err);
      return;
    }
    res.send({ code: "200", data: data });
  });
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }

});
// 7.删除用户
a.post("/deleteuser", (req, res, next) => {
  let obj = req.body;
  // console.log(obj);
  let sql = "delete from user where user_id = ?";
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
      pool.query(sql, [obj.id], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.affectedRows == 1) {
      res.send({ code: "200", msg: "删除成功!" });
    } else {
      res.send({ code: "201", msg: "删除失败!" });
    }
  });
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }

});
// 8.更新 修改用户密码
a.post("/updateuserpwd", (req, res, next) => {
  let obj = req.body;
  let sql = "update user set user_pwd = ? where user_id = ?";
  // console.log(obj)
  let id = parseInt(obj.id);
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
      pool.query(sql, [obj.pwd, id], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.affectedRows == 1) {
      res.send({ code: "200", msg: "修改成功!" });
    } else {
      res.send({ code: "201", msg: "修改失败!" });
    }
  });
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }

});
// 9.获取具体的的车辆信息
a.post("/updatecars", (req, res, next) => {
  let obj = req.body;
  // console.log(obj)
  let sql = "select * from car where car_id = ?";
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
      pool.query(sql, [obj.carid], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    if (data.length !== 0) {
      res.send({ code: "200", msg: "查询成功!", cardata: data });
    } else {
      res.send({ code: "201", msg: "暂无该车辆信息!" });
    }
  });
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }

});
// 10.更新车辆信息
a.post("/renewal", (req, res, next) => {
  let obj = req.body;
  // console.log(obj);
  let sql =
    "update car set car_name = ?,car_feature=?,car_score=?,car_price=?,car_ishot=? where car_id = ?";
  let cid = parseInt(obj.id);
  let cprice = parseInt(obj.price);
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
   pool.query(
    sql,
    [obj.name, obj.feature, obj.score, obj.price, obj.ishot, obj.id],
    (err, data) => {
      if (err) {
        next(err);
        return;
      }
      // console.log(data)
      if (data.affectedRows == 1) {
        res.send({ code: "200", msg: "修改成功!" });
      } else {
        res.send({ code: "201", msg: "修改失败!" });
      }
    }
  );   
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }

});
// 11.删除订单
a.post("/deleteorder",(req,res,next)=>{
  let obj = req.body
  console.log(obj);
  let sql = 'delete from car_order where order_id = ?'
  const token = (req.headers.authorization || "").slice(7);
  if(verifyToken(token)){
    pool.query(sql,[obj.id],(err,data)=>{
      if(data.affectedRows==1){
        res.send({"code":200,"msg":"删除成功"})
      }else{
        res.send({"code":201,"msg":"删除失败"})
      }
    })
  }else{
    res.send({"code":402,"msg":"未合法登录"})
  }
})
//***************************************//
module.exports = a;
